import { defineStore } from "pinia";
//引入接口
import { reqLogin, reqUserInfo, reLogOut } from "../../api/user";
import type { loginForm, getUserData, loginData } from '../../api/user/type'
//引用路由
import { constantRoutes, asyncRoutes, anyRoute } from '../../router/routes'
import router from "../../router";
//引入深拷贝
import _ from 'lodash'; // 使用默认导入方式引入 Lodash  
//定义过滤函数
function filterAsyncRoutes(asyncRoutes: any, routes: any) {
  return asyncRoutes.filter((item: any) => {
    if (routes.includes(item.name)) {
      if (item.children && item.children.length > 0) {
        item.children = filterAsyncRoutes(item.children, routes)
      }
      return true;
    }
  })
}
const userStore = defineStore('user', {
  state: () => {
    return {
      token: localStorage.getItem('TOKEN'),//用户唯一标识token
      menuRoutes: constantRoutes, //仓库存储生成菜单需要数组（路由）,
      username: "",
      avatar: ''
    }
  },
  actions: {
    //用户登录的方法
    async userLogin(data: loginForm) {
      const result: loginData = await reqLogin(data);
      /*     console.log(result.data); */

      /* console.log(result); */
      if (result.code == 200) {
        /*   console.log(result); */

        this.token = result.data
        localStorage.setItem('TOKEN', result.data)
        return 'ok'
      } else {
        return Promise.reject(new Error(result.data))
      }
    },
    async getUserInfo() {
      const result: getUserData = await reqUserInfo()
      /* this.username =  */
      /*    console.log(result.data.routes); */
      if (result.code == 200) {
        this.username = result.data.name
        this.avatar = result.data.avatar
        //调用过滤异步路由
        const userRoute = filterAsyncRoutes(_.cloneDeep(asyncRoutes), result.data.routes)
        this.menuRoutes = [...constantRoutes, ...userRoute, ...anyRoute];
        [...userRoute, ...anyRoute].forEach((item: any) => {
          router.addRoute(item)
        });
        //打印查看用户当前全部路由
        /*    console.log(router.getRoutes()); */

        return 'ok'
      } else {
        return Promise.reject('获取用户信息失败')
      }
    },
    async exitUserInfo() {
      const result = await reLogOut()
      /*       console.log(result); */
      if (result.code == 200) {
        localStorage.removeItem('TOKEN')
        this.token = ''
        this.username = ''
        this.avatar = ''
      }
    }
  },

  getters: {

  }
})
export default userStore